package com.geek.javase.ch15.work.custompool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CustomPoolDemo {
    public static void main(String[] args) {
        //创建线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                2 , 3 ,
                60L , TimeUnit.SECONDS ,
                new LinkedBlockingQueue<>(3) ,
                new ThreadPoolExecutor.DiscardOldestPolicy() // 拒绝策略：丢弃队列中最旧的任务
        );

        // 提交任务给线程池执行
        for (int i = 0; i < 8; i++) {
            pool.execute(new MyRun((i+1)+""));
        }

        //输出阻塞队列的信息
        BlockingQueue<Runnable> queue = pool.getQueue();
        for (Runnable runnable : queue) {
            System.out.println(runnable);
        }

        //关闭线程池
        pool.shutdown();
    }

}
//自定义任务类，实现Runnable接口模拟需要执行的任务
class MyRun implements Runnable{
    private String name;

    @Override
    public String toString() {
        return "MyRun{" +
                "name='" + name + '\'' +
                '}';
    }

    public MyRun(String name){
        this.name = name;
    }

    @Override
    public void run() {
        try{
            TimeUnit.SECONDS.sleep(1);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"执行任务"+name);
    }
}
